<?php

namespace app\index\controller;

use app\index\model\School as SchoolModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Controller;
use think\Db;
use think\Validate;

class School extends Controller
{
    //主页
    public function index(){
        extract(input());
        $where = [];
        if(isset($school_name) && !empty($school_name)){
            $where['school_name'] = ['like','%'.$school_name.'%'];
        }
        if(isset($city) && !empty($city)){
            $where['city'] = ['like','%'.$city.'%'];
        }
        $data = SchoolModel::where($where)->order('id Desc')->paginate('5');
        //halt($data);
        //分页按钮
        $page = $data->render();
        $this->assign('data',$data);
        //分页按钮
        $this->assign('page',$page);
        return $this->fetch('school');
    }
    //添加页面
    public function add(){
        return $this->fetch('add');
    }
    //添加
    public function addPostByAjax()
    {
        // 接收数据
        $data = input();
        // 在此加验证
        // 验证规则
        $rule = [
            'school_name'  => 'require',
            'city'=>'require'
        ];

        $msg = [
            'school_name.require' => '学校名称不能为空',
            'city'=>'请选择城市'
        ];

        $validate = new Validate($rule, $msg);
        $result   = $validate->check($data);

        if (true !== $result) {
            $this->error($validate->getError());
        }

        // 入库
        $add = SchoolModel::create($data);

        if ($add) {
            return json(['code' => 1, 'msg' => '添加成功']);
        } else {
            return json(['code' => 2, 'msg' => '添加失败']);
        }
    }
    //修改页面
    public function edit(){
        $id = input('id');
        $user = SchoolModel::where('id',$id)->find();
        $this->assign('user',$user);
        $this->assign('id',$id);
        return $this->fetch('edit');
    }
    //修改
    public function editPost(){
        $data = input();
        $rule = [
            'school_name'  => 'require',
            'city'=>'require'
        ];
        $msg = [
            'school_name.require' => '学校名称不能为空',
            'city'=>'请选择城市'
        ];
        $validate = new Validate($rule, $msg);
        $result   = $validate->check($data);
        if (true !== $result) {
            $this->error($validate->getError());
        }
       $edit = SchoolModel::where('id',$data['id'])->update($data);
        if($edit){
            $this->success('修改成功','school/index');
        }else{
            $this->error('修改失败');
        }
    }
    //单条删除
    public function del(){
        $id = input ('id');
        $del = SchoolModel::destroy($id);
        if($del){
            return json(['code' => 1, 'msg' => '删除成功']);
        }else{
            return json(['code' => 2, 'msg' => '删除失败']);
        }
    }
    //批量删除
    public function delete(){
        $ids = input('ids/a');
        $del = SchoolModel::destroy($ids);
        if($del){
            $this->success('删除成功','school/index');
        }else{
            $this->error('删除失败');
        }
    }
    //导出Excel
    public function exportExcel()
    {
        // 查询要导出的数据
        $data = SchoolModel::all();

        // 实例化
        $spreadsheet = new Spreadsheet();
        // 获取活动工作薄
        $sheet = $spreadsheet->getActiveSheet();

        // 获取单元格
        $cellA = $sheet->getCell('A1');
        // 设置单元格的值
        $cellA->setValue('ID');
        // 设置 A 列 列宽
        $sheet->getColumnDimension('A')->setWidth(10);
        // 设置第一行 行高
        $sheet->getRowDimension(1)->setRowHeight(20);

        $cellB = $sheet->getCell('B1');
        $cellB->setValue('学校名称');
        $sheet->getColumnDimension('B')->setWidth(40);

        $cellC = $sheet->getCell('C1');
        $cellC->setValue('所在地区');
        $sheet->getColumnDimension('C')->setWidth(15);

        // 设置样式 标题栏
        $styleArray = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '黑体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 设置样式 正文
        $styleArrayBody = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '宋体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 应用样式
        $sheet->getStyle('A1')->applyFromArray($styleArray);
        $sheet->getStyle('B1')->applyFromArray($styleArray);
        $sheet->getStyle('C1')->applyFromArray($styleArray);


        // 从 A2 开始填充数据
        foreach ($data as $k => $v) {
            $n = $k + 2;
            // 获取单元格
            $cellA = $sheet->getCell('A'.$n);
            // 设置单元格的值
            $cellA->setValue($v['id']);

            $cellB = $sheet->getCell('B'.$n);
            $cellB->setValue($v['school_name']);

            $cellC = $sheet->getCell('C'.$n);
            $cellC->setValue($v['city']);


            // 再给表格体设置样式
            $sheet->getStyle('A'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('B'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('C'.$n)->applyFromArray($styleArrayBody);

        }

        // 下载文件名
        $filename = '学校列表.xlsx';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$filename);
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }
    //导入Excel
    public function Excel_export()
    {
        // 接收文件
        $file = $_FILES['file']['tmp_name'];
        // 创建读操作
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
        // 打开文件、载入excel表格
        $spreadsheet = $reader->load($file);
        // 获取活动工作薄
        $sheet = $spreadsheet->getActiveSheet();


        // 获取总行数
        $highestRow = $sheet->getHighestRow();

        // 存放插入成功的记录
        $successLog = [];
        // 存放插入失败的记录
        $failLog = [];

        // 从第二行开始读取表格数据，循环写入数据库
        for ($i = 2; $i <= $highestRow; $i++) {
            // 第 1 次循环获取第 2列 第 2 行单元格的值，第 2 次循环获取第 3 列 第 3 行单元格的值
            $school_name = $sheet->getCellByColumnAndRow(2, $i)->getValue();
            $city = $sheet->getCellByColumnAndRow(3, $i)->getValue();
            // 假设数据表有以下字段

            $data = [
                'school_name' => $school_name,
                'city' => $city,
            ];
            $insert = SchoolModel::create($data);
            if ($insert) {
                $successLog[] = '第' . $i . '条，插入成功';
            } else {
                $failLog[] = '第' . $i . '条，插入失败';
            }
        }
        // 将成功数和失败数返回给 ajax
        return json(['success' => count($successLog), 'fail' => count($failLog)]);
    }
}